package com.blog.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.blog.dto.CommentDTO;
import com.blog.service.CommentService;
import com.blog.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/comments")
public class CommentController {
    
    private static final Logger log = LoggerFactory.getLogger(CommentController.class);
    
    @Autowired
    private CommentService commentService;
    
    /**
     * 获取文章评论列表
     */
    @GetMapping("/article/{articleId}")
    public List<CommentVO> getCommentsByArticleId(@PathVariable Long articleId) {
        return commentService.getCommentsByArticleId(articleId);
    }
    
    /**
     * 添加评论
     */
    @PostMapping
    public Long addComment(@RequestBody @Validated CommentDTO commentDTO) {
        // 使用Sa-Token获取当前登录用户ID
        StpUtil.checkLogin(); // 检查是否已登录
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 记录接收到的评论数据，帮助调试
        log.info("添加评论: userId={}, articleId={}, parentId={}, replyToUserId={}, content={}",
                userId, commentDTO.getArticleId(), commentDTO.getParentId(), 
                commentDTO.getReplyToUserId(), commentDTO.getContent());
        
        return commentService.addComment(commentDTO, userId);
    }
    
    /**
     * 删除评论
     */
    @DeleteMapping("/{commentId}")
    public Boolean deleteComment(@PathVariable Long commentId) {
        // 使用Sa-Token获取当前登录用户ID
        StpUtil.checkLogin(); // 检查是否已登录
        Long userId = StpUtil.getLoginIdAsLong();
        
        return commentService.deleteComment(commentId, userId);
    }
} 